using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using CRM.Core.MappingAttributes;

namespace CRM.Data.Common
{
    public static class ListConversionExtension
    {
        public static List<T> ConvertToList<T>(IDataReader dr)
        {
            var businessEntityType = typeof(T);
            var entities = new List<T>();
            var hashtable = new Hashtable();
            var properties = businessEntityType.GetProperties();
            foreach (var info in properties)
            {
                var v = info.GetCustomAttributes(true);
                hashtable[((ColumnMap)v.First()).ColumnName.ToUpper()] = info;
            }
            while (dr.Read())
            {
                var newObject = (T)Activator.CreateInstance(businessEntityType);
                for (var index = 0; index < dr.FieldCount; index++)
                {
                    var info = (PropertyInfo)hashtable[dr.GetName(index).ToUpper()];
                    if ((info != null) && info.CanWrite)
                    {
                        info.SetValue(newObject, dr.GetValue(index), null);
                    }
                }
                entities.Add(newObject);
            }
            dr.Close();
            return entities;
        }
    }
}